package de.slothsoft.commons.swing;

import java.text.NumberFormat;
import java.text.ParsePosition;

public final class StringParser {

    public static <T> Object parse(String string, Class<T> type) {
	if (type == String.class)
	    return string;
	if (string == null || string.trim().isEmpty())
	    return null;
	if (type == Integer.class || type == int.class)
	    return parseInteger(string);
	if (type == char[].class)
	    return string.toCharArray();

	throw new RuntimeException("Do not know how to parse string to " + type); //$NON-NLS-1$
    }

    private static Integer parseInteger(String string) {
	NumberFormat format = NumberFormat.getIntegerInstance();
	format.setParseIntegerOnly(true);
	return Integer.valueOf(((Long) parseNumber(string, format)).intValue());
    }

    private static Number parseNumber(String string, NumberFormat format) {
	ParsePosition position = new ParsePosition(0);
	// returns always Double or Long
	Number number = (Number) format.parseObject(string, position);
	if (position.getErrorIndex() >= 0)
	    throw new RuntimeException("Could not parse number: " + string); //$NON-NLS-1$
	return number;
    }

    private StringParser() {
	// I am elsewhere! (i.e. not shown)
    }

}
